//
//  RepeatWhenViewController.swift
//  iOS-RxSwift-Tutorials_Example
//
//  Created by mengru.tian on 2020/9/24.
//  Copyright © 2020 CocoaPods. All rights reserved.
//

import UIKit
import RxSwift

extension ObservableConvertibleType {
     
    //当被监视的序列（notifier）发出事件时，重新发送源序列
    func repeatWhen<O: ObservableType>(_ notifier: O) -> Observable<E> {
        return notifier.map { _ in }
            .startWith(())
            .flatMap { () -> Observable<E> in
                self.asObservable()
        }
    }
}

class RepeatWhenViewController: UIViewController {

    let disposeBag = DisposeBag()
    
    override func viewDidLoad() {
        super.viewDidLoad()

        title = "60.重复执行某个操作序列：repeatWhen"
        view.backgroundColor = .white
        
        test()
        test2()
    }
    
    func test() {
        //触发序列
        let notifier = PublishSubject<()>()
         
        //对源序列进行订阅
        Observable.of("a", "b", "!")
            .repeatWhen(notifier) //设置触发重复执行行为的监视序列
            .subscribe(onNext: {
                print($0)
            })
            .disposed(by: disposeBag)
         
        //重复两次
        notifier.onNext(())
        notifier.onNext(())
    }
    
    func test2() {
        
        let refreshButton = UIBarButtonItem(title: "刷新", style: .plain, target: nil, action: nil)
        self.navigationItem.rightBarButtonItem = refreshButton
        
        //创建URL对象
        let urlString = "http://douban.fm/j/mine/playlist?type=n&channel=1&from=mainsite"
        let url = URL(string:urlString)
        //创建请求对象
        let request = URLRequest(url: url!)
         
        //创建并发起请求
        URLSession.shared.rx.data(request: request)
            .repeatWhen(refreshButton.rx.tap) //刷新按钮点击后再次请求
            .observeOn(MainScheduler.instance)
            .subscribe(onNext: {
                data in
                let json = try! JSONSerialization.jsonObject(with: data,
                    options: JSONSerialization.ReadingOptions.mutableContainers)
                    as! [String: Any]
                let song = (json["song"] as! [[String: Any]])[0]
                let artist = song["artist"] as! String
                let title = song["title"] as! String
                self.showAlert(message: artist, title: title)
            }).disposed(by: disposeBag)
    }
    
    //显示提示信息
    func showAlert(message: String, title: String) {
        let alert = UIAlertController(title: title, message: message,
                                      preferredStyle: .alert)
        alert.addAction(UIAlertAction(title: "确定", style: .cancel))
        self.present(alert, animated: true)
    }
}
